package indi.tshoiasc.simstr.listener;

import indi.tshoiasc.simstr.config.ConfigHolder;
import indi.tshoiasc.simstr.config.ConfigLoader;
import indi.tshoiasc.simstr.utils.ItemOperate;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;

public class DamageListener implements Listener {
	private static int getLevel(ItemStack is) {
		if (!is.hasItemMeta()) {
			return -1;
		}
		ItemMeta im = is.getItemMeta();
		if (!im.hasLore()) {
			return -1;
		}
		int index = ItemOperate.lookupLoreIndex(is, "§b[强化等级]:§6§l");
		if (index == -1) {
			return -1;
		}
		String temp = (String) im.getLore().get(index);
		StringBuffer sb = new StringBuffer("§b[强化等级]:§6§l");
		int level = 0;
		for (int i = 1; i < 11; i++) {
			sb.append("✡");
			level = i;
			if (sb.toString().equals(temp)) {
				break;
			}
		}
		return level;
	}

	@EventHandler(priority = EventPriority.HIGH)
	public void modifyEntityDamage(EntityDamageByEntityEvent e) {
		if ((e.isCancelled()) || (!(e.getEntity() instanceof LivingEntity))) {
			return;
		}
		if ((e.getDamager() instanceof Player)) {
			Player damager = (Player) e.getDamager();
			ItemStack hand = damager.getItemInHand();
			ConfigHolder setting = (ConfigHolder) ConfigLoader.list.get(Integer.valueOf(hand.getTypeId()));
			if (setting == null) {
				return;
			}
			if (setting.getMode() == 1) {
				int level = getLevel(hand);
				if (level == -1) {
					return;
				}
				double damage = e.getDamage();
				e.setDamage(damage + level * ConfigHolder.addValue);
			}
		}
		if (!(e.getEntity() instanceof Player)) {
			return;
		}
		Player p = (Player) e.getEntity();
		ItemStack[] equip = p.getInventory().getArmorContents();
		int level = 0;
		ItemStack[] arrayOfItemStack1;
		double d1 = (arrayOfItemStack1 = equip).length;
		for (int i = 0; i < d1; i++) {
			ItemStack hhad = arrayOfItemStack1[i];
			ConfigHolder setting = (ConfigHolder) ConfigLoader.list.get(Integer.valueOf(hhad.getTypeId()));
			if ((setting != null) && (setting.getMode() == 2)) {
				int tempo = getLevel(hhad);
				if (level != -1) {
					level += tempo;
				}
			}
		}
		if (level == 0) {
			return;
		}
		e.setDamage(e.getDamage() - level * ConfigHolder.addValue);
	}
}
